import React, {PureComponent} from 'react';
import {connect} from 'dva';

import {Button, Card, Cascader, Form, Icon, Input, InputNumber, Modal, Radio, Select, Tooltip, Upload} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import NEditor from "../../components/NEditor/NEditor";

const FormItem = Form.Item;
const {Option} = Select;

const {TextArea} = Input;

@connect(state => ({
    shop_good: state.shop_good,
}))
@Form.create()
export default class GoodEdit extends PureComponent {
    state = {
        thumbUrl: '',
        previewVisible: false,
        previewImage: '',
        content: '',
        fileList: [],
        thumbFile: {},
        category: [],
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'shop_good/queryMenus',
        });
        this.loadGood();
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                values.content = this.state.content;
                values.id = this.props.match.params.id;
                this.props.dispatch({
                    type: 'shop_good/edit',
                    payload: values,
                    callback: () => {
                       this.loadGood();
                    },
                });
            }
        });
    }
    loadGood = () => {
        const {match, dispatch} = this.props;
        dispatch({
            type: 'shop_good/fetchService',
            payload: {id: match.params.id},
            callback: (item) => {
                const thumbfile = item.thumb.replace('https://zzbj.kooki.cn', '');
                this.state.fileList = [];
                item.photos.forEach((photo, i) => {
                    const file = {
                        uid: i,
                        status: 'ok',
                        url: photo,
                        response: {data: {url: photo, file: photo.replace('https://zzbj.kooki.cn', '')}},
                    };
                    this.state.fileList.push(file);
                });
                this.setState({
                    content: item.content,
                    thumbUrl: item.thumb,
                    thumbFile: thumbfile,
                    fileList: this.state.fileList,
                    category: item.category_data.parent ? [item.category_data.parent.id, item.category_data.id] : [item.category_data.id],
                });
                setTimeout(()=>{
                    this.refs.editor.setContent(item.content);
                },500)

            },
        });
    }

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        console.log(file);
        this.setState({
            previewImage: file.response.data.url,
            previewVisible: true,
        });
    }

    thumbUpload = (info) => {
        if (info.file.status === 'done') {
            const thumbUrl = info.file.response.data.url;
            this.setState({
                thumbUrl,
            });
            return info.file.response.data.file;
        }
    }
    photosChange = ({fileList}) => {
        this.setState({ fileList });
        return this.state.fileList;
    }
    beforeUpload = () => {

    }

    render() {
        const {shop_good: {options, item, loading}} = this.props;
        const {getFieldDecorator} = this.props.form;
        const thumbUrl = this.state.thumbUrl;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
          <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
          </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 17},
                md: {span: 14},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };
        return (
          <PageHeaderLayout title="新增商品" content="新增商品，下列的所有内容均需填写">
            <Card bordered={false}>
              <Form
                onSubmit={this.handleSubmit}
                hideRequiredMark
                style={{marginTop: 8}}
              >
                <FormItem
                  {...formItemLayout}
                  label="商品名称"
                >
                  {getFieldDecorator('name', {
                                rules: [{
                                    required: true, message: '请输入商品名称',
                                }],
                               initialValue: item.name,
                            })(
                              <Input placeholder="商品名称" />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                  商品类别
                  <em className={styles.optional}>
                      &nbsp;
                    <Tooltip title="选择需要添加到的类别">
                      <Icon type="info-circle-o" style={{marginRight: 4}} />
                    </Tooltip>
                  </em>
                    </span>
                      }
                >
                  {getFieldDecorator('category', {initialValue: this.state.category})(
                    <Cascader placeholder="选择商品分类" options={options} changeOnSelect />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="商品简介"
                >
                  {getFieldDecorator('description', {
                                rules: [{
                                    required: true, message: '请输入商品简介',
                                }],
                                initialValue: item.description,
                            })(
                              <TextArea style={{minHeight: 32}} placeholder="请输入商品简介" rows={4} />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="商品价格"
                  hasFeedback
                >
                  {getFieldDecorator('price', {
                                rules: [{
                                    required: true,
                                    message: '请输入正确的商品价格',
                                    pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                                }],
                      initialValue: item.price,
                            })(
                              <Input placeholder="商品价格" />
                            )}
                </FormItem>
                  <FormItem
                      {...formItemLayout}
                      label="赠送积分"

                  >
                      {getFieldDecorator('point', {
                          initialValue:item.point
                      })(
                          <InputNumber  />
                      )}
                  </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="运费"
                  hasFeedback
                >
                  {getFieldDecorator('ship_money', {
                          rules: [{
                              required: true,
                              message: '请输入正确的商品价格',
                              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                          }],
                      initialValue: item.ship_money,

                  })(
                    <Input placeholder="商品价格" />
                      )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="销量"
                  hasFeedback
                >
                  {getFieldDecorator('sell_num', {
                          rules: [{
                              required: true,
                              message: '请输入销量',
                          }],
                      initialValue: item.sell_num,
                      })(
                        <InputNumber min={0} />
                      )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="缩略图"
                >
                  <div className="dropbox">
                    {getFieldDecorator('thumb', {
                              valuePropName: 'thumb',
                              getValueFromEvent: this.thumbUpload,
                        initialValue: this.state.thumbFile,
                        rules: [{
                            required: true,
                            message: '请上传缩略图',
                        }],
                          })(
                            <Upload.Dragger showUploadList={false} name="file" action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                              {thumbUrl ? <img src={thumbUrl} alt="" className={styles.thumb} /> :
                              <div>
                                <p className="ant-upload-drag-icon">
                                  <Icon type="inbox" />
                                </p>
                                <p className="ant-upload-text">点击或拖拽上传</p>
                              </div>}
                            </Upload.Dragger>
                          )}
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="相册"
                >
                  <div className="dropbox">
                    {getFieldDecorator('photos', {
                              valuePropName: 'photos',
                              getValueFromEvent: this.photosChange,
                        initialValue: this.state.fileList,
                              rules: [{
                                  required: true,
                                  type: 'array',
                                  max: 5,
                                  min: 1,
                                  message: '请上传相册',
                              }],
                          })(
                            <Upload fileList={this.state.fileList} onPreview={this.handlePreview} listType="picture-card" name="file" action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                              {fileList.length >= 5 ? null : uploadButton}
                            </Upload>
                          )}
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="状态"
                >
                  {getFieldDecorator('status', {initialValue: item.status})(
                    <Radio.Group>
                      <Radio value={0}>下架</Radio>
                      <Radio value={1}>上架</Radio>
                    </Radio.Group>
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="图文详情"
                >

                  <NEditor  ref="editor" onChange={(content) => {
                      this.setState({
                          content,
                      });
                  }} value={item.content?item.content:''} />

                </FormItem>
                <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                  <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                  </Button>
                  <Button onClick={() => { this.props.form.resetFields(); }} style={{marginLeft: 8}}>重置</Button>
                </FormItem>
              </Form>
            </Card>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="图片预览" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </PageHeaderLayout>
        );
    }
}
